import { JSEncrypt } from 'jsencrypt'
// import { login, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken, KEY } from '@/utils/auth'
import http from '@/utils/axios'
import router, { resetRouter } from '@/router'
import { Local } from '@/utils/storage'

const encryptor = new JSEncrypt()
encryptor.setPublicKey(KEY)
const user = {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: Local.get('userInfo'),
    roles: [],
    topMenus: [],
    menuTree: []
  },

  mutations: {
    SET_TOKEN: (state, payload) => {
      state.token = payload
    },
    SET_USERINFO: (state, payload) => {
      state.userInfo = payload
    },
    SET_ROLES: (state, payload) => {
      state.roles = payload
    },
    SET_MENUS: (state, payload) => {
      state.menuList = payload
    },
    SET_TOP_MENUS: (state, payload) => {
      state.topMenus = payload
    },
    SET_MENU_TREE: (state, payload) => {
      state.menuTree = payload
    }
  },

  actions: {
    // 登录
    async login({ commit }, params) {
      console.log('params', params);
      const res = await http.post('/login', params)
      console.log('res', res)
      setToken(res.token)
      commit('SET_TOKEN', res.token)
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      if (Local.get('userInfo')) {
        commit('SET_USERINFO', Local.get('userInfo'))
        return
      }
      const res = await http.get('/user/info')
      commit('SET_USERINFO', res.data)
      Local.set('userInfo', res.data)
      return res.data
    },
    // 动态修改权限
    changeRoles({ dispatch }) {
      return new Promise(resolve => {
        const { data } = dispatch('getUserInfo')
        resetRouter()
        const { menu, id } = data.userInfo
        const accessRoutes = dispatch('generateRoutes', { id, menu }) // 动态修改权限后 重绘侧边菜单
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        resolve()
      })
    },
    // 登出
    logOut() {
      // return new Promise((resolve, reject) => {
        // logout(state.token)
        //   .then(() => {
        //     commit('SET_TOKEN', '')
        //     commit('SET_ROLES', [])
        //     removeToken()
        //     resolve()
        //   })
        //   .catch(error => {
        //     reject(error)
        //   })
      // })
    },
    // 前端 登出
    fedLogOut({ commit }) {
      return new Promise(resolve => {
        sessionStorage.clear(true)
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 获取用户菜单
    async getUserMenu({ commit }) {
      const res = await http.get('/user/menus')
      let topMenus = []
      let menuTree = []
      res.data.forEach(element => {
        topMenus.push({
          name: element.name,
          menuName: element.menuName,
          path: element.path,
        })
        if (element.children && element.children.length > 0) {
          if (element.module !== 'system') {
            menuTree = menuTree.concat(element)
          } else {
            menuTree = menuTree.concat(element.children)
          }
        }
      });
      commit('SET_TOP_MENUS', topMenus)
      commit('SET_MENU_TREE', menuTree)
      return res.data
    },
    // 获取用户信息
    getUserInfo1({ commit }) {
      return new Promise((resolve, reject) => {
        const userInfo = {
          currentCampusNames: '总部111',
          currentRoleId: '0ef60b0d745849f7af9a90d94c00300,f',
          currentRoleName: 'admin',
          id: '6',
          loginName: 'cg',
          // 子应用与菜单
          menu: [
            {
              appName: '系统应用',
              appPrefix: '/sub-app1',
              id: '1',
              appMenus: [
                {
                  menuName: '系统管理',
                  path: '/system',
                  icon: 'el-icon-s-tools',
                  parent: 0,
                  id: '1-2',
                  children: [
                    {
                      menuName: '用户管理',
                      path: '/system/user',
                      icon: 'el-icon-user',
                      id: '1-2-1'
                    },
                    {
                      menuName: '权限管理',
                      path: '/system/menu',
                      icon: 'el-icon-menu',
                      id: '1-2-1'
                    },
                  ]
                },
                {
                  menuName: '日志管理',
                  path: '/log',
                  icon: 'el-icon-s-platform',
                  parent: 0,
                  id: '1-4',
                  children: [
                    {
                      menuName: '操作日志',
                      path: '/log/index',
                      id: '1-4-1',
                      icon: 'el-icon-s-marketing',
                    }
                  ]
                }
              ]
            },
            {
              appName: '运营系统',
              appPrefix: '/sub-app2',
              noDisplay: true,
              appMenus: [
                {
                  menuName: '评论管理',
                  path: '/',
                  icon: 'el-icon-user',
                  children: [
                    {
                      menuName: '作业评论',
                      path: '/docs',
                      icon: 'el-icon-user',
                    }
                  ]
                },
                {
                  menuName: '课程管理',
                  path: '/about',
                  icon: 'el-icon-user'
                }
              ]
            },
            // {
            //   appName: '第三个子应用',
            //   appPrefix: '/sub-app3',
            //   // noDisplay: true,
            //   appMenus: [
            //     {
            //       menuName: '一级菜单',
            //       path: '/',
            //       icon: 'el-icon-user'
            //     },
            //     {
            //       menuName: '一级菜单',
            //       path: '/about',
            //       icon: 'el-icon-user'
            //     }
            //   ]
            // },
            // {
            //   appName: '测试重连机制',
            //   appPrefix: '/sub-app4',
            //   // noDisplay: true,
            //   appMenus: [
            //     {
            //       menuName: '1111',
            //       path: '/',
            //       icon: 'el-icon-user'
            //     },
            //     {
            //       menuName: '2222',
            //       path: '/about',
            //       icon: 'el-icon-user'
            //     }
            //   ]
            // },
          ],
          mobile: '18811117311',
          skinId: 'blackgold',
          staffNo: '111111',
          status: true,
          systemUpdateTime: '系统更新于 2020-02-20 08:07:14',
          updateBy: '超管',
          updateDate: '2020-02-20T10:46:59.000+0000',
          userName: '超管'
        }
        if (userInfo.menu && userInfo.menu.length) {
          commit('SET_ROLES', userInfo.menu)
          commit('SET_USERINFO', userInfo)
          resolve(userInfo)
        } else {
          reject()
        }
        // getUserInfo(state.token)
        //   .then(response => {
        //     const { userInfo } = response.data
        //     const { menu } = userInfo
        //     if (menu && menu.length) {
        //       // 验证返回的menu是否是一个非空数组
        //       commit('SET_ROLES', menu)
        //     } else {
        //       reject('getInfo: menu must be a non-null array !')
        //     }
        //     commit('SET_USERINFO', userInfo)
        //     resolve(response)
        //   })
        //   .catch(error => {
        //     reject(error)
        //   })
      })
    },
  }
}

export default user
